<?php
/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2016/11/29
 * Time: 下午3:27
 */

namespace common\services\myhtsq;


use common\entities\common\MyscrmOrganizationEntity;
use common\repositories\myhtsq\ErpUserRepository;
use common\services\BaseService;
use common\support\StringHelper;

class ContactService extends BaseService
{

    /**
     * 当同步完成erp_user表之后,同时将org表的交付人员信息也更新
     */
    public function updateOrganizationContact()
    {
        //取出所有GUID不为空的,并从myscrm_erp_user中更新
        $allOrg = MyscrmOrganizationEntity::find()->asArray()->all();
        foreach ($allOrg as $org) {
            $data = [];

            //同步更新org表的客户经理信息
            if (!empty($org["CustomManagerGUID"])) {
                $customUserInfo = $this->getErpUserInfo($org["CustomManagerGUID"]);
                if (false != $customUserInfo) {
                    $data["CustomManager"] = $customUserInfo["UserName"];
                    $data["CustomManagerPhone"] = $customUserInfo["MobilePhone"];
                    $data["CustomManagerEmail"] = $customUserInfo["Email"];
                }
            }

            //同步更新org表的交付人信息
            if (!empty($org["DeliverGUID"])) {
                $deliverUserInfo = $this->getErpUserInfo($org["DeliverGUID"]);
                if (false != $deliverUserInfo) {
                    $data["Deliver"] = $deliverUserInfo["UserName"];
                    $data["DeliverPhone"] = $deliverUserInfo["MobilePhone"];
                    $data["DeliverEmail"] = $deliverUserInfo["Email"];
                }
            }
            if (empty($data)) {
                continue;
            }
            $ret = MyscrmOrganizationEntity::updateAll($data, ["Id" => $org["Id"]]);
            if (false === $ret) {
                \Yii::error("更新org表交付人员信息失败:Id=" . $org["Id"]);
            }
        }
    }

    /**
     * 获取ero user信息
     * @param $userGUID
     * @return bool|\common\entities\myhtsq\ErpUserEntity
     */
    private function getErpUserInfo($userGUID)
    {
        $userInfo = ErpUserRepository::getUserById($userGUID);
        if (empty($userInfo)) {
            return false;
        }

        //处理手机号 去除+86
        $mobilePhone = StringHelper::getLastMobilePhone($userInfo["MobilePhone"]);
        $userInfo["MobilePhone"] = $mobilePhone;
        return $userInfo;
    }
}